<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\adminapi\controller\captain;

use app\admin\model\User;
use app\common\controller\BackendApi;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 队长申请管理
 *
 * @icon fa fa-circle-o
 */
class Apply extends BackendApi
{

    /**
     * CaptainApplication模型对象
     * @var \app\admin\model\CaptainApplication
     */
    protected $model = null;
    protected $statusList = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CaptainApplication;
        $this->statusList = $this->model->getStatusList();
    }


    /**
     * 查看
     */
    public function index()
    {
        $page = $this->request->request('page') ?? 1;
        $step = 10;
        $start = ($page - 1) * $step;
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
            //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $where = [];
        $count = $this->model
            ->with(['user'])
            ->where(function ($query) use($where){
                if ($where){
                    $query->where($where);
                }
            })
            ->count();

        $list = $this->model
                ->with(['user'])
                ->where(function ($query) use($where){
                    if ($where){
                        $query->where($where);
                    }
                })
                ->order('captain_application.id desc')
                ->limit($start,$step);

        foreach ($list as $row) {


        }

        $result = array("total" => $count, "rows" => $list);
        $this->success('获取成功',$result);
    }

    public function edit($ids = null)
    {
        $data = [];
        $status = $this->request->request('status');
        $reviewer_reason = $this->request->request('reviewer_reason');
        $status ? $data['status'] = $status : '';
        $status ? $data['reviewer_reason'] = $reviewer_reason : $this->error('请填写审核意见');
        $ids = $this->request->post('ids');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        if (empty($data)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($data['status'] == \app\common\model\CaptainApplication::STATUS_REVIEWED_SUCCESS) {
                User::update(['is_captain'=>\app\common\model\User::IS_CAPTION_YES,'updatetime'=>time()],['id'=>$row['user_id']]);
            }
            $row->reviewer_id = $this->auth->getAdminId();
            $params['update_time'] = time();
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
